// 初始化画布
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;

// 游戏网格数据
const gridSize = 4;
const cellSize = canvas.width / gridSize;
let grid = Array(gridSize).fill().map(() => Array(gridSize).fill(null));

// 生成初始方块
function spawnRandomTile() {
  const emptyCells = [];
  for (let y = 0; y < gridSize; y++) {
    for (let x = 0; x < gridSize; x++) {
      if (!grid[y][x]) emptyCells.push({ x, y });
    }
  }
  
  if (emptyCells.length > 0) {
    const { x, y } = emptyCells[Math.floor(Math.random() * emptyCells.length)];
    grid[y][x] = { value: Math.random() < 0.9 ? 2 : 4 };
  }
}

// 绘制游戏界面
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 绘制网格背景
  for (let y = 0; y < gridSize; y++) {
    for (let x = 0; x < gridSize; x++) {
      ctx.fillStyle = '#cdc1b4';
      ctx.fillRect(x * cellSize, y * cellSize, cellSize - 10, cellSize - 10);
      
      // 绘制方块
      if (grid[y][x]) {
        const { value } = grid[y][x];
        ctx.fillStyle = getTileColor(value);
        ctx.fillRect(x * cellSize, y * cellSize, cellSize - 10, cellSize - 10);
        
        ctx.fillStyle = '#776e65';
        ctx.font = 'bold 24px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(value, x * cellSize + cellSize / 2, y * cellSize + cellSize / 2);
      }
    }
  }
}

// 根据数值获取方块颜色（简化版）
function getTileColor(value) {
  const colors = {
    2: '#eee4da', 4: '#ede0c8', 8: '#f2b179',
    16: '#f59563', 32: '#f67c5f', 64: '#f65e3b',
    128: '#edcf72', 256: '#edcc61', 512: '#edc850',
    1024: '#edc53f', 2048: '#edc22e'
  };
  return colors[value] || '#3c3a32';
}

// 处理键盘输入（方向键）
document.addEventListener('keydown', (e) => {
  let moved = false;
  
  switch (e.key) {
    case 'ArrowUp':
      moved = moveUp();
      break;
    case 'ArrowDown':
      moved = moveDown();
      break;
    case 'ArrowLeft':
      moved = moveLeft();
      break;
    case 'ArrowRight':
      moved = moveRight();
      break;
  }
  
  if (moved) {
    spawnRandomTile();
    draw();
  }
});

// 游戏初始化
spawnRandomTile();
spawnRandomTile();
draw();
